package com.mkx.domain.vo;

import lombok.Getter;

import java.util.regex.Pattern;

/**
 * 手机号值对象
 * 封装手机号的验证和处理逻辑
 */
@Getter
public class PhoneNumber {
    
    // 中国大陆手机号正则表达式
    private static final String CHINA_PHONE_REGEX = "^1[3-9]\\d{9}$";
    private static final Pattern CHINA_PHONE_PATTERN = Pattern.compile(CHINA_PHONE_REGEX);
    
    private final String number;
    
    /**
     * 构造函数
     * @param number 手机号
     * @throws IllegalArgumentException 当手机号无效时抛出
     */
    public PhoneNumber(String number) {
        if (number == null || number.trim().isEmpty()) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        // 移除可能的空格和连字符
        String cleanedNumber = number.replaceAll("[\s-]", "");
        if (!isValid(cleanedNumber)) {
            throw new IllegalArgumentException("无效的手机号格式");
        }
        this.number = cleanedNumber;
    }
    
    /**
     * 验证手机号格式
     */
    private boolean isValid(String phone) {
        return CHINA_PHONE_PATTERN.matcher(phone).matches();
    }
    
    /**
     * 获取手机号的前三位（运营商识别码）
     */
    public String getCarrierCode() {
        if (number.length() >= 3) {
            return number.substring(0, 3);
        }
        return number;
    }
    
    /**
     * 获取手机号的中间四位
     */
    public String getMidSection() {
        if (number.length() >= 7) {
            return number.substring(3, 7);
        }
        return "";
    }
    
    /**
     * 获取手机号的最后四位
     */
    public String getLastFourDigits() {
        if (number.length() >= 4) {
            return number.substring(number.length() - 4);
        }
        return number;
    }
    
    /**
     * 获取脱敏后的手机号
     */
    public String getMaskedNumber() {
        if (number.length() == 11) {
            return number.substring(0, 3) + "****" + number.substring(7);
        }
        return number;
    }
    
    @Override
    public String toString() {
        return number;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        PhoneNumber that = (PhoneNumber) obj;
        return number.equals(that.number);
    }
    
    @Override
    public int hashCode() {
        return number.hashCode();
    }
}